using System;
using System.Drawing;
using System.Windows.Forms;

namespace 地图哇哇哇
{
   public class NotificationsManager : IDisposable
  {
    public NotificationsManager(string text, Icon icon)
    {
      NotifyIcon = new NotifyIcon();
      ContextMenu = new ContextMenu();
      NotifyIcon.Text = text;
      NotifyIcon.Icon = icon;
      NotifyIcon.ContextMenu = ContextMenu;
      NotifyIcon.Visible = true;
      NotifyIcon.Click += (EventHandler) ((sender, e) =>
      {
        EventHandler notificationIconClicked = NotificationIconClicked;
        if (notificationIconClicked == null)
          return;
        notificationIconClicked(this, e);
      });
      NotifyIcon.BalloonTipClicked += (EventHandler) ((sender, e) =>
      {
        EventHandler notificationClicked = NotificationClicked;
        if (notificationClicked == null)
          return;
        notificationClicked(this, e);
      });
    }

    public NotifyIcon NotifyIcon { get; private set; }

    public  ContextMenu ContextMenu { get; private set; }

    public void Dispose()
    {
      Dispose(true);
      GC.SuppressFinalize(this);
    }

    public event EventHandler NotificationIconClicked;

    public event EventHandler NotificationClicked;

    public void AddContextMenuItem(string text, EventHandler onClick)
    {
      ContextMenu.MenuItems.Add(new MenuItem(text, onClick));
    }

    public void ShowBalloonToolTip(string title, string text = "", int duration = 1500, ToolTipIcon icon = ToolTipIcon.Info)
    {
      NotifyIcon.ShowBalloonTip(duration, title, text, icon);
    }

    private void Dispose(bool disposing)
    {
      if (!disposing)
        return;
      if (NotifyIcon != null)
      {
        NotifyIcon.Visible = false;
        NotifyIcon.Dispose();
        NotifyIcon = null;
      }
      if (ContextMenu != null)
      {
        ContextMenu.MenuItems.Clear();
        ContextMenu.Dispose();
        ContextMenu = null;
      }
    }
  }
}